package com.cdivtc.management.controller;

import com.cdivtc.management.pojo.Result;
import com.cdivtc.management.utils.StaticString;
import com.cdivtc.management.verify.VerifyCode;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

@RestController
public class VerifyController {
    @RequestMapping("api/code")
    public String code(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //创建验证码生成器实例取得生成图片和随机字符串
        VerifyCode vc = new VerifyCode();
        BufferedImage image = vc.getImage();
        String text = vc.getText();
        //随机字符串存入session中
        System.out.println(text);
        StaticString.verifyCode = text.toLowerCase();
        HttpSession session = req.getSession();
        session.setAttribute("index_code", text);
        Cookie cookie = new Cookie("code", text);
        cookie.setPath("/");
        resp.addCookie(cookie);
        //用流传输
        OutputStream os = resp.getOutputStream();
        VerifyCode.output(image, os);
        os.flush();
        os.close();
        return text;
    }

//    @RequestMapping("/verifyCode")
//    public String verifyCode(String code, HttpServletRequest req,HttpServletResponse resp) {
//        return code.toLowerCase().equals(StaticString.verifyCode) ? "true" : "false";
//    }
}
